<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Document</title>
</head>

<body>
  <script>
    const time = (timer) => {
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve();
        }, timer);
      });
    };
    const ajax1 = () =>
      time(2000).then(() => {
        console.log(1);
        return 1;
      });
    const ajax2 = () =>
      time(1000).then(() => {
        console.log(2);
        return 2;
      });
    const ajax3 = () =>
      time(1000).then(() => {
        console.log(3);
        return 3;
      });

    function mergePromise(ajaxArray) {
      // 存放每个ajax的结果
      // let promise = Promise.resolve();
      // ajaxArray.forEach((ajax) => {
      //   // 第一次的then为了用来调用ajax
      //   // 第二次的then是为了获取ajax的结果
      //   promise = promise.then(ajax).then((res) => {
      //     data.push(res);
      //     return data; // 把每次的结果返回
      //   });
      // });
      // // 最后得到的promise它的值就是data
      // return promise;

      const data = []

      function run(index, resolve) {
        if (index >= ajaxArray.length) return resolve(data)
        ajaxArray[index]().then((res) => {
          data.push(res)
          run(++index, resolve)
        })
      }

      return new Promise((resolve, reject) => {
        run(0, resolve)
      })
    }

    mergePromise([ajax1, ajax2, ajax3]).then((data) => {
      console.log("done");
      console.log(data); // data 为 [1, 2, 3]
    });

    // 要求分别输出
    // 1
    // 2
    // 3
    // done
    // [1, 2, 3]
  </script>
</body>

</html>